{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Definition for a binary tree node.\n",
    "class TreeNode:\n",
    "    def __init__(self, x):\n",
    "        self.val = x\n",
    "        self.left = None\n",
    "        self.right = None\n",
    "from typing import List\n",
    "class Solution:\n",
    "    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n",
    "        def build(begin1, begin2, n): #n为长度\n",
    "            print(str(begin1) + \" \" + str(begin2) + \" \" + str(n))\n",
    "            if(n == 0):\n",
    "                return None\n",
    "            key = postorder[begin2+n-1]\n",
    "            idx = inorder.index(key, begin1, begin1+n)\n",
    "            len_left = idx - begin1\n",
    "            len_right = n -1 - len_left\n",
    "            root = TreeNode(key)\n",
    "            root.left = build(begin1, begin2, len_left)\n",
    "            root.right = build(begin1 + 1 + len_left, begin2 + len_left, len_right)\n",
    "            return root\n",
    "        return build(0, 0, len(inorder))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 0 5\n",
      "0 0 1\n",
      "0 0 0\n",
      "1 0 0\n",
      "2 1 3\n",
      "2 1 1\n",
      "2 1 0\n",
      "3 1 0\n",
      "4 2 1\n",
      "4 2 0\n",
      "5 2 0\n",
      "<__main__.TreeNode object at 0x000001D3269CA408>\n"
     ]
    }
   ],
   "source": [
    "a = Solution()\n",
    "inorder = [9,3,15,20,7]\n",
    "postorder = [9,15,7,20,3]\n",
    "print(a.buildTree(inorder, postorder))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
